package com.ayu.chatroom.service.impl;

import com.ayu.chatroom.constant.ChatroomConstant;
import com.ayu.chatroom.entity.Users;
import com.ayu.chatroom.entity.vo.MyFriendVo;
import com.ayu.chatroom.entity.vo.UserVo;
import com.ayu.chatroom.mapper.UsersMapper;
import com.ayu.chatroom.service.FriendsRequestService;
import com.ayu.chatroom.service.MyFriendsService;
import com.ayu.chatroom.service.UsersService;
import com.ayu.chatroom.util.FastDFSClient;
import com.ayu.chatroom.util.FileUtils;
import com.ayu.chatroom.util.QRCodeUtils;
import com.ayu.chatroom.util.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ayu
 * @since 2022-10-10
 */
@Service
@Slf4j
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {


//    @Value("${myQrCode.path:}")
//    private String pathQR;
//
//    @Value("${myFace.path:}")
//    private String pathFace;

    private final UsersMapper usersMapper;

    private final FastDFSClient fastDFSClient;

    private final QRCodeUtils qrCodeUtils;

    private final MyFriendsService myFriendsService;

    private final FriendsRequestService friendsRequestService;

    @Autowired
    public UsersServiceImpl(UsersMapper usersMapper, FastDFSClient fastDFSClient, QRCodeUtils qrCodeUtils, MyFriendsService myFriendsService, FriendsRequestService friendsRequestService) {
        this.usersMapper = usersMapper;
        this.fastDFSClient = fastDFSClient;
        this.qrCodeUtils = qrCodeUtils;
        this.myFriendsService = myFriendsService;
        this.friendsRequestService = friendsRequestService;
    }

    @Override
    public Users selectByUsername(String username) {

        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("username", username);

        return usersMapper.selectOne(queryWrapper);

    }

    @Override
    public UserVo registerOrLogin(String username, String password, String cid) {


        UserVo userVo = null;

        Users users = this.selectByUsername(username);

        if (Objects.nonNull(users)) {

            String pwd = DigestUtils.md5DigestAsHex(password.getBytes());

            if (pwd.equalsIgnoreCase(users.getPassword())) {

                userVo = new UserVo();
                BeanUtils.copyProperties(users, userVo);
            }


        } else {

            //注册流程
            Users user = new Users();
            user.setUsername(username);
            user.setNickname(username);

            //密码加密
            String pwd = DigestUtils.md5DigestAsHex(password.getBytes());
            user.setPassword(pwd);
            user.setQrcode("");
            //客户端标识
            user.setCid(cid);
            this.save(user);

            String qrcodeUrl = generateQrCode(user);

            user.setQrcode(qrcodeUrl);
            this.updateById(user);

            userVo = new UserVo();
            BeanUtils.copyProperties(user, userVo);

        }

        return userVo;
    }

    public String generateQrCode(Users user) {
        //生成二维码
//        String qrcodepath = pathQR+user.getId()+"qrcode.png";
        String qrcodepath = user.getId()+"qrcode.png";
//        String qrcodepath = "C:\\Users\\Administrator\\Desktop\\xx\\" + user.getId() + "qrcode.png";

        qrCodeUtils.createQRCode(qrcodepath, "ele_qrcode:" + user.getUsername());
        MultipartFile multipartFile = FileUtils.fileToMultipart(qrcodepath);

        String qrcodeUrl = "";

        try {

            qrcodeUrl = fastDFSClient.uploadQRCode(multipartFile);

        } catch (Exception e) {

            log.error(e.getMessage());
        }

        return qrcodeUrl;
    }


    @Override
    public Users uploadFaceBase64(String userId, String faceData) {
//        String userFacePath = pathFace+userId+"userFaceBase64.png";
        String userFacePath = userId+"userFaceBase64.png";
//        String userFacePath = "C:\\Users\\Administrator\\Desktop\\arrow.jpg";
        Users user = new Users();
        try {
            FileUtils.base64ToFile(userFacePath, faceData);
            MultipartFile multipartFile = FileUtils.fileToMultipart(userFacePath);

            String url = fastDFSClient.uploadBase64(multipartFile);

//            log.info("头像地址：" + url);
//            String thumb = "_150x150.";
//            String[] arr = url.split("\\.");
//            String thumbImgUrl = arr[0] + thumb + arr[1];

            //阿里云的缩略图只需要在图片地址后面加?x-oss-process=image/resize,m_fill,h_120,w_120
            String thumbImgUrl = url+"?x-oss-process=image/resize,m_fill,h_150,w_150";

            user.setId(userId);
            user.setFaceImageBig(url);
            user.setFaceImage(thumbImgUrl);
            this.updateById(user);

        } catch (Exception e) {
            log.error(e.getMessage());
        }

        return user;
    }

    @Override
    public R searchFriend(String myUserId, String friendUserName) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", friendUserName);
        Users one = this.getOne(queryWrapper);
        //* 1.搜索的用户如果不存在，则返回【无此用户】
        //* 2.搜索的账号如果是你自己，则返回【不能添加自己】
        //* 3.搜索的朋友已经是你好友，返回【该用户已经是你的好友】
        if (Objects.isNull(one)) {
            return R.error().message("用户不存在");
        }
        if (myUserId.equalsIgnoreCase(one.getId())) {
            return R.error().message("不能添加自己");
        }
        //查询我的朋友列表
        Integer count = myFriendsService.verifyMyFriendExist(myUserId, one.getId());
        if (count > 0) {
            return R.error().message("该用户已经是你的好友");
        }
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(one, userVo);
        return R.ok().data(userVo);
    }

    @Override
    public List<MyFriendVo> operFriendRequest(String acceptUserId, String sendUserId, Integer operType) {

        //operType 0 代表忽略 删除好友请求 1 代表同意 删除好友请求 且双向添加好友
        friendsRequestService.deleteRequest(acceptUserId, sendUserId);
        friendsRequestService.deleteRequest(sendUserId, acceptUserId);

        if (ChatroomConstant.ONE.equals(operType)) {
            //双向添加好友
            myFriendsService.addFriends(acceptUserId, sendUserId);
            myFriendsService.addFriends(sendUserId, acceptUserId);

        }


        return myFriendsService.getFriendsList(acceptUserId);
    }




}
